package com.cynteka.cyfoman.ui;

import com.cynteka.cyfoman.core.RoleFilter;
import com.cynteka.cyfoman.core.RoleProvider;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;

import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.Iterator;

/**
 * User: Sergey
 * Date: 08.08.11
 * Time: 12:50
 */
public class ComponentHelper implements BeanFactoryAware {
    private BeanFactory beanFactory;

    public Container create(Container container, java.util.List children) {
        return create(container, children, new ArrayList());

    }

    public Container create(Container container, java.util.List children, java.util.List constraints) {
        RoleProvider roleProvider = beanFactory == null ? null : (RoleProvider)beanFactory.getBean(RoleProvider.ROLE_PROVIDER_KEY);
        Iterator constraintIter = constraints.iterator();
        for(Object oChild : children) {
            if(oChild instanceof RoleFilter && roleProvider != null) {
                RoleFilter roleFilter = (RoleFilter) oChild;
                if(!roleProvider.hasAtLeastOneRole(roleFilter.getRoles())) {
                    continue;
                } else {
                    oChild = roleFilter.getWrapppedObject();
                }
            }

            if(oChild instanceof Component) {
                Component child = (Component) oChild;
                Object constraint = constraintIter.hasNext() ? constraintIter.next() : null;
                if(constraint != null)
                    container.add(child, constraint);
                else
                    container.add(child);
            } else if(oChild instanceof Action) {
                Action action = (Action) oChild;
                if(container instanceof JToolBar) {
                    JToolBar toolBar = (JToolBar) container;
                    toolBar.add(action);
                } else if(container instanceof JMenu) {
                    JMenu jMenu = (JMenu) container;
                    jMenu.add(action);
                }
            }
        }
        return container;
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }
}
